import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:nim_core/nim_core.dart';

class Chat_searchLogic extends GetxController {
  TextEditingController editingController = TextEditingController();
  String toAccountId = '';

  List<NIMMessage>? searchData = [];
  List<NIMUser> userInfo = [];

  @override
  void onInit() {
    super.onInit();

    var a = Get.arguments;
    if (a != null) {
      toAccountId = a['toAccountId'];
    }
  }

  startSearch() async {
    MessageSearchOption option = MessageSearchOption(limit: 0, searchContent: editingController.text);

    NIMResult<List<NIMMessage>> result = await NimCore.instance.messageService.searchMessage(NIMSessionType.p2p, toAccountId, option);
    searchData = result.data;
    // update();
    List<Future<NIMResult<NIMUser>>> tasks = [];
    for (NIMMessage message in searchData ?? []) {
      Future<NIMResult<NIMUser>> task = NimCore.instance.userService.getUserInfo(message.fromAccount ?? '');
      tasks.add(task);
    }

    if (tasks.isNotEmpty) {
      userInfo.clear();
      List<NIMResult<NIMUser>> results = await Future.wait(tasks);
      for (NIMResult result in results ?? []) {
        if (result.data != null) {
          userInfo.add(result.data);
        }
      }
      update();
    } else {
      update();
    }
  }
}
